package com.example.yang.yixin.Activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.yang.yixin.R;
import com.example.yang.yixin.Views.InputView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class CreateBanKeActivity extends BaseActivity {
    private InputView input_bk_password,input_bk_classname,input_bk_coursename,input_bk_stunum,input_bk_requested;
    private Button btn_create_bk;
    private ImageView mIv_back;
    private String responseMsg = "";
    private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟
    private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟
    private List<Integer> list=new ArrayList();
    private static int size1=0;
    View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_ban_ke);
        initView();
        mIv_back=findViewById(R.id.iv_back);
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(CreateBanKeActivity.this,MeActivity.class);
                startActivity(intent);
            }
        });

    }

    private void initView() {
        initNarvBar(true,"创建班课",false);
        input_bk_password=findViewById(R.id.input_bk_password);
        input_bk_classname=findViewById(R.id.input_bk_classname);
        input_bk_coursename=findViewById(R.id.input_bk_coursename);
        input_bk_stunum=findViewById(R.id.input_bk_stunum);
        input_bk_requested=findViewById(R.id.input_bk_requested);
    }

    public void OnCreateClick(View view) {
        Thread Threadinformation=new Thread(new Threadcourse());
        getServerData();
        final ProgressDialog progressDialog=new ProgressDialog(CreateBanKeActivity.this);
        progressDialog.setTitle("友课");
        progressDialog.setMessage("努力记录中...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    super.run();
                    Thread.sleep(2000);
                    progressDialog.dismiss();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Threadinformation.start();

    }
    class Threadcourse extends Thread {
        @Override
        public void run() {
            String username=getIntent().getStringExtra("data");
            String bkpassword=input_bk_password.getInputStr();
            String classname=input_bk_classname.getInputStr();
            String coursename = input_bk_coursename.getInputStr();
            String num = input_bk_stunum.getInputStr();
            String requested= input_bk_requested.getInputStr();
            Message msg = handler.obtainMessage();
            String sign="0";
            String phonecontrol="0";
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if((username.equals(""))||(classname.equals(""))||(coursename.equals(""))||(num.equals(""))||(requested.equals(""))){
                msg.what=3;
                handler.sendMessage(msg);
            }
            else {
                if(size1==0) {
                    boolean loginValidate = loginServer(bkpassword, username, classname, coursename, num, requested, sign, phonecontrol);

                    if (loginValidate) {
                        if (responseMsg.equals("")) {

                            msg.what = 0;
                            handler.sendMessage(msg);

                        } else {
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }

                    } else {
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                }else{
                    msg.what=4;
                    handler.sendMessage(msg);
                }
            }
        }
    }
    private boolean loginServer(String bkpassword ,String username ,String classname, String coursename,String num,String requested,String sign,String phonecontrol)
    {
        boolean loginValidate = false;
        //使用apache HTTP客户端实现
        String urlStr = "http://47.106.141.161/MyFirstAndroidApp/CourseInsert";
        HttpPost request = new HttpPost(urlStr);

        //如果传递参数多的话，可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //添加用户名和密

        params.add(new BasicNameValuePair("bkpassword",bkpassword));
        params.add(new BasicNameValuePair("username",username));
        params.add(new BasicNameValuePair("classname",classname));
        params.add(new BasicNameValuePair("coursename",coursename));
        params.add(new BasicNameValuePair("num",num));
        params.add(new BasicNameValuePair("requested",requested));
        params.add(new BasicNameValuePair("sign",sign));
        params.add(new BasicNameValuePair("phonecontrol",phonecontrol));


        try
        {
            //设置请求参数
            request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            HttpClient client = getHttpClient();
            //执行请求返回相应
            HttpResponse response = client.execute(request);

            //判断是否请求成功
            if(response.getStatusLine().getStatusCode()==200)
            {
                loginValidate = true;
                //获得响应信息
                responseMsg = EntityUtils.toString(response.getEntity());
                System.out.println(responseMsg);
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return loginValidate;
    }
    public HttpClient getHttpClient()
    {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpParams);
        return client;
    }
    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case 0:
                    Snackbar.make(getWindow().getDecorView(),"创建成功！快去加入吧",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                    break;
                case 1:
                    Snackbar.make(getWindow().getDecorView(),"创建失败！稍后再试",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                        }
                    }).show();
                    break;
                case 2:
                    Snackbar.make(getWindow().getDecorView(),"网络开小差了哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                        }
                    }).show();
                    break;
                case 3:
                    Snackbar.make(getWindow().getDecorView(),"信息未填写完整哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                        }
                    }).show();
                    break;
                case 4:
                    Snackbar.make(getWindow().getDecorView(),"班课口令已被占用哦！",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                        }
                    }).show();
                break;
            }

        }
    };
    private void  getServerData() {
        String bkpassword=input_bk_password.getInputStr();
        String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/BankepasswordServlet?bkpassword="+bkpassword;
        RequestQueue mQueue = Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    int size=Integer.parseInt(response.getString("size")) ;
                    size1=size;
                } catch (JSONException e) {

                    Log.e("json错误",e.getMessage());
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };
        mQueue.add(jsonObjectRequest);

    }

}





